package com.runner.suporte;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataHelper extends SQLiteOpenHelper {
	private static final String DATABASE_NAME = "runner.db";
	private static final int DATABASE_VERSION= 1 ;
	private static final String TABLE_NAME = "exercicio";
	private SQLiteDatabase db;
	
	public DataHelper (Context context){
		super(context, DATABASE_NAME,null,DATABASE_VERSION);
		this.db = this.getWritableDatabase();
	}
	@Override
	public void onCreate(SQLiteOpenHelper db){
		db.execSQL ("CREATE TABLE" + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENTE, " + " data TEXT, tempo TEXT, percurso REAL, tipo INTEGER)");
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
	}
	public long inserir(Exercicio exercicio){
		ContentValues cv = new ContentValues();
		cv.put("data", exercicio.getData());
		cv.put("tempo", exercicio.getTempo());
		cv.put("percurso", exercicio.getPercurso());
		cv.put("tipo", exercicio.getTipo());
		return db.insert(TABLE_NAME, "data", cv);
	}
	public void eliminarUltExercicio(){
		int id = -1;
		Cursor result = db.rawQuery("SELECT max(id) FROM" + TABLE_NAME, null);
		if (result.moveToFirst() && !result.isAfterLast()){
			id=result.getInt(0);
		}
		if (result != null && !result.isClosed()){
			result.close();
		}
		if (id > -1) {
			this.db.delete(TABLE_NAME, "ID="  + id, null);
		}
}
		public List<Exercicio>obterTodos(){
			List<Exercicio>lista = new ArrayList<Exercicio>();
			Cursor result = db.rawQuery(
					"SELECT id, data, tempo, percurso, tipo FROM" + TABLE_NAME + " ORDER BY data", null);
			if (result.moveToFirst()){
				while (!result.isAfterLast()){
					lista.add(new Exercicio(result.getInt(0),result.getString(1), result.getString(2),result.getFloat(3),(byte)result.getInt(4)));
					result.moveToNext();
				}
			}
			result.close();
			return lista;
		}
		public float[]obterMedias(){
			float medAtual = 0.0f;
			float[] media = new float [6];
			Cursor result = db.rawQuery(
					"SELECT tempo, percurso, tipo FROM" + TABLE_NAME, null);
			if (result.moveToFirst()){
				int pos = 0 ;
				while (!result.isAfterLast()){
					medAtual = Funcoes.convHHMMtoMIN(result.getString(0)) / result.getFloat(1);
					pos = (result.getInt(2) == 0)?0:3;
					if (media[pos] == 0){
						media[pos]=medAtual;
					} else {
						media[pos] = (media[pos] + medAtual) / 2;
					}
					if (media[pos + 1] == 0 || medAtual > media[pos +1]){
						media[pos + 1] = medAtual;
					}
					if (media[pos + 2] == 0 || medAtual < media[pos +2]){
						media[pos + 2] = medAtual;
				}
					result.moveToNext();
			}
		}
			result.close();
			return media;
		}
}
